package edu.colorado.karl.devices;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.colorado.karl.databases.ErrorDatabaseResult;
import edu.colorado.karl.databases.LongTermDatabase;
import edu.colorado.karl.databases.SensorResponse;

/**
 * Represents the Solar Panels device.  This device is responsible for
 * obtaining and displaying information about the solar panels.
 * @author Michael Knudson
 * @version 4/27/08
 */
public class SolarPanels {
	//	Used for log4j logging
	private static final Log log = LogFactory.getLog(SolarPanels.class);
	
	/**
	 * Sole Constructor
	 */
	public SolarPanels() {
		
	}
	
	/**
	 * Returns the current temperature of the Solar Panels.
	 * @return a double representing the current average temperature of the
	 * Solar Panels.
	 */
	public double getCurrentTemperature() {
		LongTermDatabase ltdb = new LongTermDatabase();
		double temp = -666;		// Solar Panel Sensor Temperatures
		
		//	Get the solar panel temperature from the database
		ArrayList<SensorResponse> ltl = ltdb.getSolarPanelTemperature();
		
		for (SensorResponse response : ltl) {
			if(response.getName().equals("PVT"))
				temp = Double.parseDouble(response.getValueString());
		}
		
		if(temp == -666) {
			log.error("Current State unable to find current Solar Panel Temperatures.");
			temp = 0.0;
			ErrorDatabaseResult.activateError(ErrorDatabaseResult.LONG_TERM_FAIL);
		}
		
		return temp;
	}
	
	/**
	 * Returns the last supply and return temperatures recorded in the 
	 * Long-Term Database for the solar panels.  If an error occurs while 
	 * retrieving a temperature, the Long_Term_Fail error is set and the value 
	 * "0.0" is returned for that temperature.
	 * @return a two-element double array containing temperatures.
	 * Index 0 contains the return temperature while index 1 contains the supply
	 * temperature.
	 */
	public double[] getFlowTemperatures() {
		LongTermDatabase ltdb = new LongTermDatabase();
		double[] temps = new double[2];
		temps[0] = -666;
		temps[1] = -666;
		
		//	Get tank temperatures from the LongTerm database
		ArrayList<SensorResponse> ltl = ltdb.getSolarPanelSupplyTemperatures();

		for (SensorResponse response : ltl) {
			if(response.getName().equals("Return"))
				temps[0] = Double.parseDouble(response.getValueString());
			else if(response.getName().equals("Supply"))
				temps[1] = Double.parseDouble(response.getValueString());
		}

		if(temps[0] == -666) {
			log.error("Current State unable to find current Solar Panel Return Temperature.");
			temps[0] = 0.0;
			ErrorDatabaseResult.activateError(ErrorDatabaseResult.LONG_TERM_FAIL);
		}
		if(temps[1] == -666) {
			log.error("Current State unable to find current Solar Panel Supply Temperature.");
			temps[1] = 0.0;
			ErrorDatabaseResult.activateError(ErrorDatabaseResult.LONG_TERM_FAIL);
		}
		
		return temps;
	}
}
